package com.vf.cloud.paas.app.master.api.render.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.jfinal.kit.StrKit;
import com.vf.cloud.paas.app.master.common.domain.RenderAgent;
import com.vf.cloud.paas.app.master.common.domain.RenderAgentGpu;
import com.vf.cloud.paas.app.master.common.domain.RenderAgentRelay;
import com.vf.cloud.paas.app.master.common.domain.RenderAgentSignalling;
import com.vf.cloud.paas.app.master.common.domain.User;
import com.vf.cloud.paas.app.master.common.domain.UserAgent;
import com.vf.cloud.paas.common.datasource.annotation.Tx;
import com.vf.cloud.paas.common.log.annotation.RLog;
import com.vf.cloud.paas.common.security.annotation.TokenRequired;
import com.vf.cloud.paas.common.util.DateUtil;
import com.vf.cloud.paas.common.util.R;
import com.vf.cloud.paas.common.util.UuidUtil;
import com.vf.cloud.paas.common.util.WebUtils;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/render/agent")
public class RenderAgentController {
	

	@RLog(value = "获取渲染服务列表",type = "user")
	@TokenRequired
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public R<List<RenderAgent>> list(HttpServletRequest request, @RequestBody RenderAgent param) {
		User user = WebUtils.getCurUser(request);
		
		if(user==null) {
			return R.expired();
		}

		if(StrKit.equals("administrator", user.getUsername())) {
			
			String sqlExceptSelect = " from " + RenderAgent.TABLE_NAME + "  a WHERE 1= 1 ";
			if (!StrKit.isBlank(param.getName())) {
				sqlExceptSelect += " and ( name like '%" + param.getName() + "%' or ip like '%" + param.getName() + "%' ) ";
			}
			sqlExceptSelect += "  ORDER BY   a.modify_time desc ";
			List<RenderAgent> renderAgents=RenderAgent.dao.find("select *  " + sqlExceptSelect);
			for(RenderAgent renderAgent:renderAgents) {
				renderAgent.setChildren(RenderAgentGpu.dao.find("select a.* from "+RenderAgentGpu.TABLE_NAME+ " a where a.agent_id=? order by a.index asc ",renderAgent.getId()));
				renderAgent.setRelays(RenderAgentRelay.dao.find("select * from "+RenderAgentRelay.TABLE_NAME+" where id=?",renderAgent.getId()));
				renderAgent.setSignallings(RenderAgentSignalling.dao.find("select * from "+RenderAgentSignalling.TABLE_NAME+" where id=?",renderAgent.getId()));
			
			}
			return R.ok(renderAgents);
			
		}else {
			String sqlExceptSelect = "";
			if(StrKit.equals(user.getPid(),"-1")){
				 sqlExceptSelect = " from " + RenderAgent.TABLE_NAME + "  a WHERE a.id in (select agent_id from master_user_agent where user_id='"+user.getId()+"'   ) ";

			}else {
				 sqlExceptSelect = " from " + RenderAgent.TABLE_NAME + "  a WHERE a.id in (select agent_id from master_user_agent where user_id='"+user.getPid()+"'   ) ";
			}
			if (!StrKit.isBlank(param.getName())) {
				sqlExceptSelect += " and ( name like '%" + param.getName() + "%' or ip like '%" + param.getName() + "%' ) ";
			}
			sqlExceptSelect += "  ORDER BY   a.modify_time desc ";
			List<RenderAgent> renderAgents=RenderAgent.dao.find("select *  " + sqlExceptSelect);
			for(RenderAgent renderAgent:renderAgents) {
				renderAgent.setChildren(RenderAgentGpu.dao.find("select a.* from "+RenderAgentGpu.TABLE_NAME+ " a where a.agent_id=? and a.index in (select agent_gpu_index from "+UserAgent.TABLE_NAME+" where agent_id=? and user_id=? )  order by a.index asc ",renderAgent.getId(),renderAgent.getId(),user.getId()));
				renderAgent.setRelays(RenderAgentRelay.dao.find("select * from "+RenderAgentRelay.TABLE_NAME+" where id=?",renderAgent.getId()));
				renderAgent.setSignallings(RenderAgentSignalling.dao.find("select * from "+RenderAgentSignalling.TABLE_NAME+" where id=?",renderAgent.getId()));
			}
			return R.ok(renderAgents);
		}
	}

	@RLog(value = "保存渲染服务",type = "user")
	@TokenRequired
	@Tx
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<RenderAgent> save(HttpServletRequest request, @RequestBody RenderAgent renderAgent) {
		try {
			User user = WebUtils.getCurUser(request);

			if (StrKit.notBlank(renderAgent.getId())) {
				renderAgent.setModifyUserId(user.getCreateUserId());
				renderAgent.setModifyTime(DateUtil.getLocalDateTime());
				if (renderAgent.update()) {
					RenderAgentRelay renderAgentRelay=RenderAgentRelay.dao.findById(renderAgent.getId());
					if(renderAgentRelay==null) {
						renderAgentRelay=new RenderAgentRelay();
						renderAgentRelay.setId(renderAgent.getId());
						renderAgentRelay.setAgentId(renderAgent.getId());
						renderAgentRelay.setTurnPort(19303);
						renderAgentRelay.setStunPort(19302);
						renderAgentRelay.setUsername("admin");
						renderAgentRelay.setPassword("rs@123");
						renderAgentRelay.setIp("127.0.0.1");
						renderAgentRelay.setEnabled("-1");
						renderAgentRelay.save();
					}
					
					RenderAgentSignalling renderAgentSignalling=RenderAgentSignalling.dao.findById(renderAgent.getId());
					if(renderAgentSignalling==null) {
						renderAgentSignalling=new RenderAgentSignalling();
						renderAgentSignalling.setId(renderAgent.getId());
						renderAgentSignalling.setAgentId(renderAgent.getId());
						renderAgentSignalling.setStreamerIdleTimeout(5);
						renderAgentSignalling.setStreamerPort(6601);
						renderAgentSignalling.setPlayerPort(6602);
						renderAgentSignalling.setStreamerIp("127.0.0.1");
						renderAgentSignalling.setPlayerIp("127.0.0.1");
						renderAgentSignalling.save();
					}
					return R.ok(renderAgent);
				} else {
					return R.failed();
				}
			} else {
				renderAgent.setId(UuidUtil.getUUID());
				renderAgent.setCreateUserId(user.getId());
				renderAgent.setCreateTime(DateUtil.getLocalDateTime());
				//中继服务
				RenderAgentRelay renderAgentRelay=new RenderAgentRelay();
				renderAgentRelay.setId(renderAgent.getId());
				renderAgentRelay.setAgentId(renderAgent.getId());
				renderAgentRelay.setTurnPort(19303);
				renderAgentRelay.setStunPort(19302);
				renderAgentRelay.setUsername("admin");
				renderAgentRelay.setPassword("rs@123");
				renderAgentRelay.setIp("127.0.0.1");
				renderAgentRelay.setEnabled("-1");
				
				
				RenderAgentSignalling renderAgentSignalling=new RenderAgentSignalling();
				renderAgentSignalling.setId(renderAgent.getId());
				renderAgentSignalling.setAgentId(renderAgent.getId());
				renderAgentSignalling.setStreamerIdleTimeout(5);
				renderAgentSignalling.setStreamerPort(6601);
				renderAgentSignalling.setPlayerPort(6602);
				renderAgentSignalling.setStreamerIp("127.0.0.1");
				renderAgentSignalling.setPlayerIp("127.0.0.1");
				
				if (renderAgent.save()) {
					renderAgentRelay.save();
					renderAgentSignalling.save();
					return R.ok(renderAgent);
				} else {
					return R.failed();
				}
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@RLog(value = "删除渲染服务",type = "user")
	@TokenRequired
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public R<String> delete(@RequestBody RenderAgent param) {
		if (param == null) {
			return R.failed("参数必填.");
		}
		if (RenderAgent.dao.deleteById(param.getId())) {
			return R.ok();
		}
		return R.failed();
	}
	
	
	@RLog(value = "保存GPU路数限制",type = "user")
	@TokenRequired
	@Tx
	@RequestMapping(value = "/limit", method = RequestMethod.POST)
	public R<RenderAgentGpu> save(HttpServletRequest request, @RequestBody RenderAgentGpu renderAgentGpu) {
		try {
			if (StrKit.notBlank(renderAgentGpu.getId())) {
				if (renderAgentGpu.update()) {
					return R.ok(renderAgentGpu);
				} else {
					return R.failed();
				}
			} else {
				renderAgentGpu.setId(UuidUtil.getUUID());
				if (renderAgentGpu.save()) {
					return R.ok(renderAgentGpu);
				} else {
					return R.failed();
				}
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

}
